<template>
    <div>
        <div style="margin-top: 15px;">
            <Button type="primary" class="md-add-jh" @click='addTaskBtn'>添加验证任务</Button>
        </div>
        <Table :columns="taskCol" :data="taskList" style="margin-top: 15px;"></Table>
        <div style="display: flex;justify-content: center;margin: 15px 0">
            <Page :total=taskTotal :page-size="pageSize" :current="page" show-total show-elevator @on-change="taskChangePage"/>
        </div>
        <!-- 验证任务 -->
        <Modal
            v-model="taskModel" width="600"
            :mask-closable="false"
            :footer-hide='true'
            :title="title">
            <Form ref="formV" :model="formV" :rules="formVRule" :label-width="120" >
                <FormItem label="名称" prop="name">
                    <Input v-model.trim="formV.name" placeholder="请输入验证任务名称"></Input>
                </FormItem>
                <FormItem label="任务顺序" prop="taskOrder">
                    <InputNumber :min='1' v-model="formV.taskOrder" :editable="false"></InputNumber>
                </FormItem>
                <!-- 验证方式 -->
                <FormItem label="验证流程类型" prop="verificationType">
                    <RadioGroup v-model="formV.verificationType"  @on-change='changeVerificationType' >
                        <Radio label="auto">自动验证</Radio>
                        <Radio label="user">人工验证</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="模式" prop="matchMode" v-if="formV.verificationType=='auto'">
                    <RadioGroup v-model="formV.matchMode">
                        <Radio label="equal">相同</Radio>
                        <Radio label="contain">包含</Radio>
                        <Radio label="regex">正则</Radio>
                        <Radio label="bool">布尔</Radio>
                        <Radio label="list">多规则</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="规则" prop="matchRule" v-if="formV.matchMode!='list' && formV.verificationType=='auto'">
                    <Input style="width: 300px;font-size: 12px;vertical-align: top;" v-model="formV.matchRule" type="textarea" 
                    :autosize="{minRows: 2,maxRows: 5}" :placeholder="formV.matchMode=='bool'?'true或false':'请填写规则'" 
                    clearable :maxlength="200"></Input>
                </FormItem>
                <FormItem label="多个规则" prop="ruleList" v-if="formV.matchMode=='list' && formV.verificationType=='auto'">
                    <Input style="width: 300px;font-size: 12px;vertical-align: top;" v-model="formV.ruleList" type="textarea" 
                    :autosize="{minRows: 2,maxRows: 5}" placeholder="多个规则请以;隔开" 
                    clearable :maxlength="200"></Input>
                </FormItem>
                <FormItem label="验证方式" prop="userVerificationType" v-if="formV.verificationType=='user'">
                    <RadioGroup v-model="formV.userVerificationType">
                        <Radio label="delay">末尾验证</Radio>
                        <Radio label="realTime">实时验证</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="验证任务类型" prop="checkType">
                    <RadioGroup v-model="formV.checkType" @on-change='changeCheckType' >
                        <Radio label="train" >训练任务</Radio>
                        <Radio label="collect" :disabled="formV.verificationType == 'user'">采集任务</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem :label="formV.checkType=='train'?'训练任务':'采集任务'" prop="checkIds">
                    <Select filterable :transfer="true" v-model="formV.checkIds" style="width: 300px" :placeholder="formV.checkType=='train'?'训练任务':'采集任务'" 
                        filterable clearable multiple>
                        <Option  v-for="aa in taskFormList" :key="aa.id" :value="aa.id" @click.native="ddd" :title="aa.name">{{aa.name}}</Option>
                    </Select>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="submitBtn('formV')" :loading='modelLoading'>确定</Button>
                    <Button @click="resetBtn('formV')" style="margin-left: 8px">重置</Button>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>
<script>
    import $ from 'jquery'
    import {checkTaskList,addCheckTask,colTaskList,modifyCheckTask,delCheckTask,taskList} from '@/api/train.js'
    export default {
        data () {
            const validateTask = (rule, value, callback)=>{
                if(value.length <= 0){
                    callback(new Error('请选择任务'));
                }else{
                    callback();
                }
            }
            const validateOrder = (rule, value, callback)=>{
                if(value.length <= 0){
                    callback(new Error('请设置任务顺序'));
                }else{
                    callback();
                }
            }
            return {
                setBtnState:'',
                sceneID:this.$route.query.id,
                projectId:this.$route.query.projectId,
                isImp:'',
                // 任务
                taskTotal:0,
                taskCol:[
                    {
                        type: 'index',
                        width: 60,
                        align:'center'
                    },
                    {
                        title:'任务名称',
                        key:'name',
                        align:'center'
                    },
                    {
                        title:'任务类型',
                        key:'taskType',
                        align:'center'
                    },
                    {
                        title:'创建者',
                        key:'creatorName',
                        align:'center'
                    },
                    {
                        title:'创建时间',
                        key:'createTime',
                        align:'center'
                    },
                    {
                        title:'操作',
                        key:'action',
                        align:'left',
                        width:200,
                        render:(h,params)=>{
                            let flag = true
                            return h('a',{
                                attrs: {
                                    disabled:flag?false:true,
                                },
                                style: {
                                    'display': 'flex',
                                    'justify-content': 'flex-start',
                                    'align-items': 'center',
                                },
                            },[
                                h('Poptip',
                                    {
                                        props: {
                                            confirm: true,
                                            transfer:true,
                                            title: '确定要删除这个任务吗？'
                                        },
                                        on: {
                                            'on-ok': ()=>{
                                                this.delTask(params.row)
                                            },
                                            'on-cancel': ()=>{

                                            }
                                        }
                                    },
                                    [
                                        h('img', {
                                            attrs: {
                                                src: flag?require('../../../assets/project/delNote-h.png'):require('../../../assets/project/delNote-d.png'),
                                            },
                                            style: {
                                                cursor: 'pointer',
                                                'margin-right':'5px',
                                                'vertical-align': 'middle',
                                                width:'16px',
                                                height:'16px',
                                                display:'inline-block',
                                            },
                                        }),
                                    ],
                                ),
                                h('div', {
                                    on: {
                                        'click': ()=>{
                                            this.modifyTask(params.row)
                                        },
                                    },
                                    style:{
                                        'margin-left':'15px',
                                    }
                                }, [
                                    h('img', {
                                        attrs: {
                                            src: flag?require('../../../assets/project/modifys-h.png'):require('../../../assets/project/modifys.png'),
                                        },
                                        style: {
                                            cursor: 'pointer',
                                            'margin-right':'5px',
                                            'vertical-align': 'middle',
                                            width:'16px',
                                            height:'16px',
                                            display:'inline-block',
                                        },
                                    }),
                                ])
                            ])
                        }
                    }
                ],
                taskList:[],
                page:1,
                pageSize:10,
                // 添加
                currentNodeTaskData:[],
                taskModel:false,
                modelLoading:false,
                isCreat:true,
                title:'创建验证任务',
                formV:{
                    taskOrder:1,
                    action:"verifySuccess",
                    failedAction:"verifyFailed",
                    expression:"and",
                    name: "",
                    taskType: "check",
                    trainingId: "",
                    waitFor:"any",
                    checkType:'train',
                    checkIds:[],
                    matchMode:"equal",
                    matchProperty:"value",
                    matchRule:"",
                    ruleList:'',
                    verificationType:'auto',
                    userVerificationType:'delay',
                },
                formVRule:{
                    name: [
                        { required: true,min:1,max: 64, message: '名称长度为1—64个字符', trigger: 'change' },
                    ],
                    taskOrder: [
                        { required: true,validator: validateOrder},
                    ],
                    matchMode: [
                        { required: true,trigger: 'change',message: '请选择模式'},
                    ],
                    checkType: [
                        { required: true,trigger: 'change',message: '请选择类型'},
                    ],
                    checkIds: [
                        { required: true,validator: validateTask,},
                    ],
                },
                modifyTaskId:'',
                taskFormList:[],
                // 添加多个
                vmsForm:{
                    vms: [
                        {
                            matchMode:"equal",
                            matchProperty:"value",
                            matchRule:"",
                            id:'',
                        }
                    ]
                },
                // 采集任务
                colTaskList:[],
                colPageSize:1000,
                colPage:1,
                trainTaskList:[],
            }
        },
        created(){
            
        },
        mounted(){
            this.getTaskList()
            this.getColData()
            this.getTrainTaskList()
        },
        watch: {
            // hidebtn(newVal) {
            //     this.setBtnState = newVal //对父组件传过来的值进行监听，如果改变也对子组件内部的值进行改变
            // },
        },
        methods:{
            // 任务列表
            getTaskList(){
                let params = {
                    pageIndex:this.page,
                    pageSize:this.pageSize,
                    trainingId:this.sceneID,
                }
                checkTaskList(params)
                .then(res=>{
                    if(res.data.code === 1){
                        this.taskList = res.data.data.records
                        this.taskTotal = res.data.data.total
                    }else{
                        this.taskList = []
                        this.taskTotal = 0
                    }
                })
                .catch(err=>{
                    console.log(err)
                })
            },
            taskChangePage(val){
                this.page = val
                this.getTaskList()
            },
            // 添加任务
            addTaskBtn(){
                this.title = '创建验证任务'
                this.isCreat = true
                this.taskModel = true
                this.formV = {
                    taskOrder:1,
                    action:"verifySuccess",
                    failedAction:"verifyFailed",
                    expression:"and",
                    name: "",
                    taskType: "check",
                    trainingId: "",
                    waitFor:"any",
                    checkType:'train',
                    checkIds:[],
                    matchMode:"equal",
                    matchProperty:"value",
                    matchRule:"",
                    ruleList:'',
                    verificationType:'auto',
                    userVerificationType:'delay',
                },
                this.formV.taskOrder = this.taskTotal+1
            },
            submitBtn(name){
                if(this.isCreat){
                    this.creatSub(name)
                }else{
                    this.modifySub(name)
                }   
            },
            // 重置按钮
            resetBtn(name){
                this.$refs[name].resetFields();
            },
            handleAddVms(){
                this.vmsForm.vms.push({
                    matchMode:"equal",
                    matchProperty:"value",
                    matchRule:"",
                    collectId:'',
                });
            },
            handleRemoveVms(index){
                if(this.vmsForm.vms.length === 1){
                    this.$Message.info('请最少添加一项配置')
                    return false
                }else {
                    this.vmsForm.vms.splice(index,1)
                }
            },
            // 创建提交
            creatSub(name){
                this.$refs[name].validate((valid) =>{
                    if(valid){
                        let params =  {}
                        if(this.formV.verificationType === 'auto'){  // 如果是自动验证
                            params = {
                                action:"verifySuccess",
                                failedAction:"verifyFailed",
                                expression:"or",
                                waitFor:"any",
                                matchMode:this.formV.matchMode,
                                matchProperty:this.formV.matchProperty,
                                taskType: 'check',
                                checkType: this.formV.checkType,
                                trainingId: this.sceneID,
                                name: this.formV.name,
                                checkIds:this.formV.checkIds.join(","),
                                taskOrder:this.formV.taskOrder,
                                verificationType:this.formV.verificationType,
                            }
                            if(this.formV.matchMode == 'list'){
                                params.ruleList = this.formV.ruleList.split(';')
                                params.ruleList = JSON.stringify(params.ruleList)
                            }else{
                                params.matchRule =  this.formV.matchRule
                            }
                            if(params.checkType == 'train'){
                                params.matchProperty = 'submitContent'
                            }else{
                                params.matchProperty = 'value'
                            }
                        }else if(this.formV.verificationType === 'user'){  // 如果是人工验证
                            params = {
                                action:"verifySuccess",
                                checkIds:this.formV.checkIds.join(","),
                                failedAction:"verifyFailed",
                                expression:"or",
                                waitFor:"any",
                                taskType: 'check',
                                checkType: this.formV.checkType,
                                trainingId: this.sceneID,
                                name: this.formV.name,
                                taskOrder:this.formV.taskOrder,
                                verificationType:this.formV.verificationType,
                                userVerificationType:this.formV.userVerificationType,
                            }
                        }
                        this.modelLoading = true
                        addCheckTask(params)
                            .then(res=>{
                                if(res.data.code == 1){
                                   this.$Message.success({
                                       content:'创建成功',
                                       duration:3,
                                   })
                                   this.taskModel = false
                                   this.getTaskList()
                                }else {
                                    this.$Message.error({
                                       content:res.data.message,
                                       duration:5,
                                   })
                                }
                                this.modelLoading = false
                            })
                            .catch(err=>{
                                this.modelLoading = false
                                this.$Message.error('服务器连接失败！')
                            })
                    }else {
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            // 修改任务
            modifyTask(row){
                this.modifyTaskId = row.id
                console.log(row)
                if(row.checkType == 'train'){
                    this.taskFormList = this.trainTaskList
                }else{
                    this.taskFormList = this.colTaskList
                }
                this.formV = {
                    "name": row.name,
                    action:"verifySuccess",
                    failedAction:"verifyFailed",
                    expression:"or",
                    waitFor:"any",
                    matchMode:row.matchMode || '',
                    matchProperty:row.matchProperty || '',
                    taskType: 'check',
                    checkType: row.checkType,
                    matchRule: row.matchRule || '',
                    ruleList: row.ruleList ? JSON.parse(row.ruleList).join(";"):'',
                    checkIds:row.checkIds.split(","),
                    taskOrder:row.taskOrder,
                    verificationType:row.verificationType || '',
                    userVerificationType:row.userVerificationType || '',
                }
                this.title = '修改任务'
                this.isCreat = false
                this.taskModel = true
            },
            // 修改提交
            modifySub(name){
                this.$refs[name].validate((valid) =>{
                    if(valid){
                        let params = {}
                        if(this.formV.verificationType === 'auto'){  // 如果是自动验证
                            params = {
                                'id':this.modifyTaskId,
                                action:"verifySuccess",
                                failedAction:"verifyFailed",
                                expression:"or",
                                waitFor:"any",
                                matchMode:this.formV.matchMode,
                                matchProperty:this.formV.matchProperty,
                                taskType: 'check',
                                checkType: this.formV.checkType,
                                trainingId: this.sceneID,
                                name: this.formV.name,
                                checkIds:this.formV.checkIds.join(","),
                                taskOrder:this.formV.taskOrder,
                                verificationType:this.formV.verificationType,
                            }
                            if(this.formV.matchMode == 'list'){
                                params.ruleList = this.formV.ruleList.split(';')
                                params.ruleList = JSON.stringify(params.ruleList)
                            }else{
                                params.matchRule =  this.formV.matchRule
                            }
                            if(params.checkType == 'train'){
                                params.matchProperty = 'submitContent'
                            }else{
                                params.matchProperty = 'value'
                            }
                        }else if(this.formV.verificationType === 'user'){  // 如果是人工验证
                            params = {
                                'id':this.modifyTaskId,
                                action:"verifySuccess",
                                checkIds:this.formV.checkIds.join(","),
                                failedAction:"verifyFailed",
                                expression:"or",
                                waitFor:"any",
                                taskType: 'check',
                                checkType: this.formV.checkType,
                                trainingId: this.sceneID,
                                name: this.formV.name,
                                taskOrder:this.formV.taskOrder,
                                verificationType:this.formV.verificationType,
                                userVerificationType:this.formV.userVerificationType,
                            }
                        }
                        this.modelLoading = true
                        modifyCheckTask(params)
                            .then(res=>{
                                if(res.data.code == 1){
                                   this.$Message.success({
                                       content:'修改成功',
                                       duration:3,
                                   })
                                   this.taskModel = false
                                   this.getTaskList()
                                }else {
                                    this.$Message.error({
                                       content:res.data.message,
                                       duration:5,
                                   })
                                }
                                this.modelLoading = false
                            })
                            .catch(err=>{
                                this.modelLoading = false
                                this.$Message.error('服务器连接失败！')
                            })
                    }else {
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            // 删除任务
            delTask(row){
                delCheckTask(row.id)
                .then(res=>{
                    if(res.data.code == 1){
                        this.$Message.success({
                            content:'删除成功',
                            duration:3,
                        })
                        this.getTaskList()
                    }else{
                        this.$Message.error({
                            content:res.data.message,
                            duration:5,
                        })
                    }
                })
                .catch(err=>{
                    console.log(err)
                })
            },
            // 采集任务
            getColData(){
                let params = {
                    pageIndex:this.colPage,
                    pageSize:this.colPageSize,
                    trainingId:this.sceneID,
                }
                colTaskList(params)
                .then(res=>{
                    if(res.data.code === 1){
                        this.colTaskList = res.data.data.records
                        if(this.formV.checkType == 'collect'){
                            this.taskFormList = this.colTaskList
                        }
                    }else{
                        this.taskList = []
                        this.taskTotal = 0
                    }
                })
                .catch(err=>{
                    console.log(err)
                })
            },
            // 训练任务
            getTrainTaskList(){
                let params = {
                    pageIndex:1,
                    pageSize:10000,
                    trainingId:this.sceneID,
                }
                taskList(params)
                .then(res=>{
                    if(res.data.code === 1){
                        this.trainTaskList = res.data.data.records
                        if(this.formV.checkType == 'train'){
                            this.taskFormList = this.trainTaskList
                        }
                    }
                })
                .catch(err=>{
                    console.log(err)
                })
            },
            changeCheckType(val){
                if(val == 'train'){
                    this.taskFormList = this.trainTaskList
                }else{
                    this.taskFormList = this.colTaskList
                }
            },
            changeVerificationType(val){
                if(val === 'user'){
                    this.formV.checkType  = 'train'
                    this.taskFormList = this.trainTaskList
                }
            },
            ddd(e){
                e.preventDefault()
                e.stopPropagation();
            },
        }
    }
</script>
<style scoped>
    .pageStyleVm{
        text-align: center
    }
</style>

